<template>
<div class="activityList">
  <search-block>
    <template slot="button">
      <el-button type="primary" @click="search(true)">查询</el-button>
      <el-button type="primary" @click="addActivity">添加活动</el-button>
    </template>
    <el-form inline :model="model" label-width="100px" @submit.native.prevent>
      <el-form-item label="活动标题:">
        <el-input v-model="model.title"></el-input>
      </el-form-item>
    </el-form>
  </search-block>
  <y-table
    ref="table"
    border
    pagination
    :getDataWay="getDataWay"
    :columns="columns"
  >
    <el-table-column slot="qrcodeEndTime" label="二维码过期时间" align="center" header-align="center" width="120">
      <template v-slot="{row}">
        <template v-if="row.process !== '2'">
          <div v-html="alarmTime(row.qrcodeEndTime)"></div>
        </template>
      </template>
    </el-table-column>
    <el-table-column slot="isCharge" label="是否缴费" align="center" header-align="center" width="80">
      <template v-slot="{row}">
        <span v-if="row.isCharge === '0'" class="y-warning">收费</span>
        <span v-if="row.isCharge === '1'" class="y-info">不收费</span>
      </template>
    </el-table-column>
    <el-table-column slot="process" label="活动状态" align="center" header-align="center" width="120">
      <template v-slot="{row}">
        <span v-if="row.process === '0'" class="y-warning">报名中</span>
        <span v-if="row.process === '1'" class="y-success">进行中</span>
        <span v-if="row.process === '2'" class="y-info">已结束</span>
        <span v-if="row.process === '3'">报名结束</span>
      </template>
    </el-table-column>
    <el-table-column slot="status" label="发布" align="center" header-align="center" width="80">
      <template v-slot="{row}">
        <el-popconfirm
          v-if="row.process !== '2'"
          :title="row.status === '1' ? `是否确认发布？` : `是否取消发布？`"
          @confirm="publish(row, row.status === '1')"
        >
          <el-switch
            disabled
            slot="reference"
            v-model="row.status"
            active-value="0"
            inactive-value="1"></el-switch>
        </el-popconfirm>
        <el-switch
          v-else
          disabled
          slot="reference"
          v-model="row.status"
          active-value="0"
          inactive-value="1"></el-switch>
      </template>
    </el-table-column>
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="165">
      <template v-slot="{row}">
        <div class="wrap-table-buttons">
          <el-button size="mini" @click="showUser(row)">查看人员</el-button>
          <el-button type="primary" size="mini" v-if="row.process !== '2'" @click="editActivity(row)">编辑</el-button>
          <el-button size="mini" v-else @click="editActivity(row, 'VIEW')">查看</el-button>
<!--          <el-popconfirm
            v-if="row.status === '0' && row.process === '0'"
            title="是否确认停止报名？"
            @confirm="updateProcess(row, '3')">
            <el-button slot="reference" type="primary" size="mini">停止报名</el-button>
          </el-popconfirm>-->
          <el-popconfirm
            v-if="row.status === '0' && row.process === '3'"
            title="是否确认开始活动？"
            @confirm="updateProcess(row, '1')">
            <el-button slot="reference" type="primary" size="mini">活动开始</el-button>
          </el-popconfirm>
          <el-popconfirm
            v-else-if="row.status === '0' && row.process === '1'"
            title="是否确认结束活动？"
            @confirm="updateProcess(row, '2')">
            <el-button slot="reference" type="primary" size="mini">活动结束</el-button>
          </el-popconfirm>
          <div v-else style="width: 80px"></div>
          <el-popconfirm
            title="是否确认删除该活动？"
            @confirm="delActivity(row)">
            <el-button slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
        </div>
      </template>
    </el-table-column>
  </y-table>
  <y-form
    ref="yForm"
    v-model="forms.formModel"
    :visible.sync="forms.showForm"
    :title="forms.formTypeTitle[forms.formsType]"
    :show-button="forms.formsType !== 'VIEW'"
    destroy-on-close
    width="900px"
    :form-attrs="formAttrs"
    :columns="formColumns"
    @ensure="ensureModel">
  </y-form>
  <el-dialog
    :title="`【${userForms.row.title}】报名人员`"
    class="force-inner-scroll"
    :visible.sync="userForms.show"
    @opened="openUserList"
    destroy-on-close
    width="800px">
    <activity-user-list ref="userList">

    </activity-user-list>
  </el-dialog>
</div>
</template>

<script>
import activityUserList from "./activityUserList";
export default {
  name: "activityList",
  components: { activityUserList },
  computed: {
    getDataWay() {
      return {
        dataType: 'url',
        data: this.$api.applet.activityPage,
        param: this.model
      }
    },
    formAttrs(){
      return {
        labelWidth: '160px',
        rules: {
          title: [{required: true, message: "请输入活动标题", trigger: "blur"}],
          picUrl: [{required: true, message: "请上传活动图片", trigger: "change"}],
          qrcodeUrl: [{required: true, message: "请上传群二维码图片", trigger: "change"}],
          isCharge: [{required: true, message: "请选择是否收费", trigger: "change"}],
          endTime: [{required: true, message: "请选择报名截止时间", trigger: "change"}],
          startTime: [{required: true, message: "请选择活动开始时间", trigger: "change"}],
          qrcodeEndTime: [{required: true, message: "请选择群二维码过期时间", trigger: "change"}],
          content: [{required: true, message: "请输入活动详情", trigger: "blur"}]
        },
        disabled: this.forms.formsType === 'VIEW'
      }
    },
    formColumns(){
      return [
        {
          label: "活动标题",
          prop: "title",
          comp:{
            compType: 'input',
            attrs:{
              maxlength: 30,
              showWordLimit: true
            }
          }
        },
        {
          label: "活动图片",
          prop: "picUrl",
          comp:{
            compType: 'YUploadImg',
            attrs:{
              url: this.forms.formModel.picUrl ? [{
                url: this.forms.formModel.picUrl,
                id: this.forms.formModel.attachmentId
              }] : [],
              valueType: "ObjectArray",
              businessSysModuleCode: "ACTIVITY",
              limit: 1,
              disabled: this.forms.formsType === 'VIEW',
              reUpload: true,
              cropperOptions:{
                fixedNumber: [25, 12]
              }
            },
            listeners:{
              update: this.updateModel
            }
          }
        },
        {
          label: "活动最大人数",
          prop: "scopeUser",
          comp:{
            compType: 'input-number',
            attrs:{
              stepStrictly: true,
              min: 1
            }
          }
        },
        {
          label: "可选物品数量",
          prop: "scopePer",
          comp:{
            compType: 'input-number',
            attrs:{
              stepStrictly: true,
              min: 0,
              max: 2
            }
          }
        },
        {
          label: "是否收费",
          prop: "isCharge",
          comp:{
            compType: 'select',
            options: [{
              label: '收费',
              value: '0',
            },{
              label: '不收费',
              value: '1',
            }]
          }
        },
        {
          label: "活动费用(元)",
          prop: "charge",
          vIf: this.forms.formModel.isCharge === '0',
          rules: [
            {required: true, message: "请输入活动费用", trigger: "blur"},
            {min: 0.01, type: 'number', message: "请输入活动费用", trigger: "blur"}
          ],
          comp:{
            compType: 'input-number',
            attrs:{
              stepStrictly: true,
              step: 0.01,
              min: 0
            }
          }
        },
        {
          label: "报名截止日期",
          prop: "endTime",
          comp:{
            compType: 'datePicker',
            attrs: {
              type: "datetime",
              pickerOptions:{
                disabledDate(time) {
                  return time.getTime() < Date.now();
                }
              },
              valueFormat: 'yyyy-MM-dd HH:mm:ss'
            }
          }
        },
        {
          label: "活动开始日期",
          prop: "startTime",
          comp:{
            compType: 'datePicker',
            attrs: {
              type: "datetime",
              pickerOptions:{
                disabledDate: (function(time) {
                  return !this.forms.formModel.endTime || time.getTime() < new Date(this.forms.formModel.endTime);
                }).bind(this)
              },
              valueFormat: 'yyyy-MM-dd HH:mm:ss'
            }
          }
        },
        {
          label: "群二维码",
          prop: "qrcodeUrl",
          comp:{
            compType: 'YUploadImg',
            attrs:{
              url: this.forms.formModel.qrcodeUrl ? [{
                url: this.forms.formModel.qrcodeUrl,
                id: this.forms.formModel.qrcodeId
              }] : [],
              valueType: "ObjectArray",
              businessSysModuleCode: "ACTIVITY",
              limit: 1,
              disabled: this.forms.formsType === 'VIEW',
              reUpload: true,
              cropperOptions:{
                fixed: false
              }
            },
            listeners:{
              update: this.updateModel2
            }
          }
        },
        {
          label: "群二维码过期时间",
          prop: "qrcodeEndTime",
          comp:{
            compType: 'datePicker',
            attrs: {
              type: "date",
              valueFormat: 'yyyy-MM-dd 00:00:00'
            }
          }
        },
        {
          label: "活动详情",
          prop: "content",
          comp:{
            compType: 'YRichText',
            attrs: {
              businessSysModuleCode: 'ACTIVITY',
              disabled: this.forms.formsType === 'VIEW',
            }
          }
        }
      ]
    }
  },
  data(){
    return{
      model:{
        title: ''
      },
      columns: [
        {
          label: "名称",
          prop: "title",
          minWidth: 120
        },
        {
          label: "已报名人数/总人数",
          prop: "scopeUser",
          minWidth: 120,
          formatter(row){
            return row.registeredNum + '/' + row.scopeUser;
          }
        },
        {
          label: "报名截止时间",
          prop: "endTime",
          minWidth: 180
        },
        {
          label: "活动开始时间",
          prop: "startTime",
          minWidth: 180
        },
        {
          prop: "qrcodeEndTime",
          template: true
        },
        {
          prop: "isCharge",
          template: true
        },
        {
          prop: "process",
          template: true
        },
        {
          prop: "status",
          template: true
        }
      ],
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加活动',
          'EDIT': '编辑活动',
          'VIEW': '查看活动'
        },
        formModel:{
          title: '',
          attachmentId: '',
          picUrl: '',
          qrcodeId: '',
          qrcodeUrl: '',
          isCharge: '',
          charge: '',
          content: '',
          scopePer: '',
          scopeUser: '',
          startTime: '',
          endTime: '',
          qrcodeEndTime: ''
        },
        currentForm: null,
        showForm: false
      },
      userForms:{
        row: {},
        show: false
      }
    }
  },
  methods:{
    resetForm() {
      Object.keys(this.forms.formModel).map(key => {
        this.forms.formModel[key] = this.forms.currentForm ? this.forms.currentForm[key] : '';
      })
    },
    search(jumpToFirst){
      this.$refs['table'].loadData(this.model, jumpToFirst);
    },
    alarmTime(time){
      //该时间与当前时间相差多少天
      let minus = new Date(time) - new Date();
      let minusDay = minus / (1000*60*60*24);
      if(minusDay < 0) return '<span class="y-danger">已过期</span>';
      if(minusDay <= 3) return `<span class="y-warning">${Math.ceil(minusDay)}天后过期</span>`;
      else return `<span>${Math.ceil(minusDay)}天后过期</span>`;
    },
    addActivity(){
      this.forms.formsType = 'ADD';
      this.forms.currentForm = null;
      this.resetForm();
      this.forms.showForm = true;
    },
    editActivity(row, type = 'EDIT'){
      this.$yAxios({
        url: this.$api.applet.queryActivity,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        this.forms.formsType = type;
        info.activityInfo.content = info.cmsCommonContent.content;
        this.forms.currentForm = info.activityInfo;
        this.resetForm();
        this.forms.showForm = true;
      })
    },
    delActivity(row){
      this.$yAxios({
        url: this.$api.applet.removeActivity,
        data:{
          ids: [row.id]
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.search();
      })
    },
    showUser(row){
      this.$set(this.userForms, 'row', row);
      this.userForms.show = true;
    },
    openUserList(){
      this.$refs['userList'].search(this.userForms.row.id);
    },
    updateModel({type, file}){
      switch(type) {
        case 'delete': {
          this.forms.formModel.attachmentId = '';
          this.forms.formModel.picUrl = '';
          break;
        }
        case 'edit': case 'add':{
          this.forms.formModel.attachmentId = file.id;
          this.forms.formModel.picUrl = file.name;
          this.$refs['yForm'].$refs['form'].validateField('picUrl');
          break;
        }
      }
    },
    updateModel2({type, file}){
      switch(type) {
        case 'delete': {
          this.forms.formModel.qrcodeId = '';
          this.forms.formModel.qrcodeUrl = '';
          break;
        }
        case 'edit': case 'add':{
          this.forms.formModel.qrcodeId = file.id;
          this.forms.formModel.qrcodeUrl = file.name;
          this.$refs['yForm'].$refs['form'].validateField('qrcodeUrl');
          break;
        }
      }
    },
    publish(row, bool){
      this.$yAxios({
        url: this.$api.applet.publishActivity,
        data:{
          ids: [row.id],
          status: bool ? '0' : '1'
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: bool ? '发布成功' : '成功取消发布'
        });
        this.search();
      })
    },
    ensureModel(form){
      let newForm;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
      }else{
        newForm = form;
      }
      this.$yAxios({
        url: this.$api.applet.saveActivity,
        data: newForm
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.search(this.forms.formsType === 'ADD');
      })
    },
    updateProcess(row, process){
      this.$yAxios({
        url: this.$api.applet.activityProcess,
        data:{
          ids: [row.id],
          status: process
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '操作成功'
        });
        this.search();
      })
    }
  }
}
</script>

<style scoped>

</style>
